package com.example.demo.config;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.Map;

/**
 * @author Rocket
 * @version 10.1.0
 * @date 2021-10-11 6:11 PM
 */
public class WebSocketInterceptor implements HandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
        ServletServerHttpRequest reqS = (ServletServerHttpRequest) serverHttpRequest;
        StringBuilder buf = new StringBuilder();
        HttpServletRequest req = reqS.getServletRequest();
        buf.append(req.getProtocol()).append("://").append(req.getRequestURL())
                        .append(req.getRequestURI()).append(req.getPathInfo()).append(req.getRemotePort());

        ServletServerHttpResponse repS = (ServletServerHttpResponse) serverHttpResponse;
        HttpServletResponse rep = repS.getServletResponse();
        Collection<String> headers = rep.getHeaderNames();
        for(String str: headers) {
            System.out.println(str + ":" + rep.getHeader(str));
        }

        System.out.println("握手开始 : " + buf.toString());
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
        System.out.println("握手完成");
    }
}
